package com.wang.common.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.Button;

import com.wang.mandkey.R;

public class CoverButton extends Button {
	private Drawable mFrame;
	private Rect mFrameBounds = new Rect();
	
	public CoverButton(Context context) {
		this(context, null);
	}

	public CoverButton(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public CoverButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CoverButton);
		
		Drawable drawable = a.getDrawable(R.styleable.CoverButton_coverDrawable);
		if(drawable == null) {
			mFrame = context.getResources().getDrawable(android.R.color.transparent);
		} else {
			mFrame = drawable;
		}
		mFrame.setCallback(this);
		a.recycle();
	}

	@Override
	protected boolean verifyDrawable(Drawable who) {
		return super.verifyDrawable(who) || (who == mFrame);
	}

	@Override
	protected void drawableStateChanged() {
		super.drawableStateChanged();
		if (mFrame != null) {
			int[] drawableState = getDrawableState();
			mFrame.setState(drawableState);
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		final Rect frameBounds = mFrameBounds;
		if (frameBounds.isEmpty()) {
			final int w = getWidth();
			final int h = getHeight();

			frameBounds.set(0, 0, w, h);
			mFrame.setBounds(frameBounds);
		}

		mFrame.draw(canvas);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mFrameBounds.setEmpty();
	}
}
